package com.javacv.plus.extensions.image.steps;

import com.javacv.plus.core.processor.ProcessorContext;
import com.javacv.plus.core.processor.ProcessorStep;
import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.image.ProcessorResult;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.opencv.opencv_core.Mat;

import static org.bytedeco.opencv.global.opencv_core.*;

/**
 * 图像翻转处理步骤
 * 支持水平翻转、垂直翻转、以及双向翻转
 */
@Slf4j
public class FlipStep implements ProcessorStep<ImageProcessor, ProcessorResult> {
    
    public enum FlipType {
        HORIZONTAL("水平翻转", 1),
        VERTICAL("垂直翻转", 0),
        BOTH("水平垂直翻转", -1);
        
        private final String description;
        private final int flipCode;
        
        FlipType(String description, int flipCode) {
            this.description = description;
            this.flipCode = flipCode;
        }
        
        public String getDescription() {
            return description;
        }
        
        public int getFlipCode() {
            return flipCode;
        }
    }
    
    private final FlipType flipType;
    
    public FlipStep(FlipType flipType) {
        this.flipType = flipType;
    }
    
    @Override
    public ProcessorResult execute(ImageProcessor processor, ProcessorContext context) throws Exception {
        Mat currentImage = context.getAttribute("currentImage");
        if (currentImage == null || currentImage.empty()) {
            throw new IllegalStateException("当前图像为空，无法进行翻转");
        }
        
        Mat flippedImage = new Mat();
        
        try {
            flip(currentImage, flippedImage, flipType.getFlipCode());
            context.setAttribute("currentImage", flippedImage);
            
            log.info("图像翻转完成: {}", flipType.getDescription());
            return null;
            
        } catch (Exception e) {
            if (flippedImage != null) {
                flippedImage.release();
            }
            throw new RuntimeException("图像翻转失败: " + flipType.getDescription(), e);
        }
    }
    
    @Override
    public String getStepName() {
        return "Flip-" + flipType.name();
    }
    
    @Override
    public int getPriority() {
        return 55; // 在基本处理之后，滤镜之前
    }
} 